package com.msb.mall.carts.interceptor;

import com.msb.common.constant.AuthConstant;
import com.msb.common.dto.MemberDTO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义拦截器：获取session中的用户信息
 */
public class AuthInterceptor implements HandlerInterceptor {

    // 本地线程对象
    public static ThreadLocal<MemberDTO> threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 通过httpSession获取当前登录的用户信息
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthConstant.AUTH_SESSION_REDIS);
        if (null != attribute){
            threadLocal.set((MemberDTO)attribute);
            return true;
        }
        // session中不存在登录信息，返回登录
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG,"请先登录");
        response.sendRedirect("http://auth.msb.com/login.html");
        return false;
    }
}
